import bean.MagneticNode;

import java.io.*;
import java.util.Scanner;

public class MagneticDemo{

    private static String getLoc;
    private static double avgX;
    private static double avgY;
    private static double avgZ;

    public static void main(String[] args) throws IOException {

        MagneticNode node = new MagneticNode();

        Scanner in = new Scanner(System.in);
        String path = in.nextLine();
        String fileContent = readFile(path);
        System.out.println(getLoc);

        String nodeBase[] = getLoc.split(",");
        node.setLocX(Integer.parseInt(nodeBase[1]));
        node.setLocY(Integer.parseInt(nodeBase[2]));
        node.setDirection(nodeBase[0]);
        System.out.println(fileContent);
        contentHandler(fileContent);
        node.setMagX(avgX);
        node.setMagY(avgY);
        node.setMagZ(avgZ);
        System.out.println(node.toString());
    }

    /**
     * 读取磁场文件
     * @param filePath 文件路径
     * @return string字符串
     */
    public static String readFile(String filePath){
        StringBuilder builder = new StringBuilder();
        try {
            String encoding="UTF-8";
            File file=new File(filePath);
            if(file.isFile() && file.exists()){ //判断文件是否存在
                InputStreamReader read = new InputStreamReader(new FileInputStream(file),encoding);//考虑到编码格式
                BufferedReader bufferedReader = new BufferedReader(read);
                getLoc = bufferedReader.readLine();
                String lineTxt;
                int count = 0;
                while((lineTxt = bufferedReader.readLine()) != null){
                    count++;
                    lineTxt = count + "," + lineTxt + "\n";
                    builder.append(lineTxt);
                }
                read.close();
            }else{
                System.out.println("找不到指定的文件");
            }
        } catch (Exception e) {
            System.out.println("读取文件内容出错");
            e.printStackTrace();
        }
        return builder.toString();
    }

    private static void contentHandler(String content) {
        String splitContent[] = content.split("\n");
        int n = splitContent.length;
        double xSum = 0, ySum = 0, zSum = 0;
        for (int i = 0; i < n; i++) {
            String dataDetails[] = splitContent[i].split(",");
            xSum = Double.parseDouble(dataDetails[1]) + xSum;
            ySum = Double.parseDouble(dataDetails[2]) + ySum;
            zSum = Double.parseDouble(dataDetails[3]) + zSum;
        }
        avgX = xSum / n;
        avgY = ySum / n;
        avgZ = zSum / n;
    }
}
